﻿import Vue from 'vue'
import utils from './utils.js'
import { WXJs } from './url.js'
import { GetChatJsApiConfig } from 'api/web'

// 加载公众号参数
var ___IsRunGetWxJsConfig = false
var ___IsWxJsReady = false
var __IsWxJsError = false
// var __originUrl = document.URL
function GetWxJsConfig(callback) {
  // 没有wxjs则加载wxjs
  var webInfo = Vue.prototype.$webInfo || 10053
  console.log(utils)
  console.log(webInfo)
  if (typeof (wx) === 'undefined') {
    utils.loadScript(WXJs, function () {
      GetWxJsConfig(callback)
    })
    return
  }
  // 判断环境是否为微信浏览器
  if (utils.wechat().isWechat) {
    if (___IsWxJsReady) {
      if (callback && callback instanceof Function) {
        callback()
      }
      return
    }
    if (___IsRunGetWxJsConfig) {
      var timer = setInterval(function () {
        if (___IsWxJsReady) {
          if (callback && callback instanceof Function) {
            callback()
          }
          clearInterval(timer)
        } else if (__IsWxJsError) {
          clearInterval(timer)
        }
      }, 100)
      return
    }

    ___IsRunGetWxJsConfig = true

    if (window.WeixinJSBridge && WeixinJSBridge.invoke) {
      WeixinJSBridgeReadyCallback(callback)
    } else {
      document.addEventListener('WeixinJSBridgeReady', function () {
        WeixinJSBridgeReadyCallback(callback)
      }, false)
    }
  }

  function WeixinJSBridgeReadyCallback(callback) {
    var jsApiList = [
      'checkJsApi',
      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'onMenuShareQQ',
      'onMenuShareWeibo',
      'onMenuShareQZone',
      'updateAppMessageShareData',
      'updateTimelineShareData',
      'hideMenuItems',
      'showMenuItems',
      'hideAllNonBaseMenuItem',
      'showAllNonBaseMenuItem',
      'translateVoice',
      'startRecord',
      'stopRecord',
      'onVoiceRecordEnd',
      'playVoice',
      'onVoicePlayEnd',
      'pauseVoice',
      'stopVoice',
      'uploadVoice',
      'downloadVoice',
      'chooseImage',
      'previewImage',
      'uploadImage',
      'downloadImage',
      'getNetworkType',
      'openLocation',
      'getLocation',
      'hideOptionMenu',
      'showOptionMenu',
      'closeWindow',
      'scanQRCode',
      'chooseWXPay',
      'openProductSpecificView',
      'addCard',
      'chooseCard',
      'openCard',
      'openAddress'
    ]
    var url = document.URL
    // ios下去掉#后面的内容   非常重要，不然会报无效签名
    if (url.indexOf('#') > -1 && window.navigator.userAgent.toLowerCase().indexOf('iphone') !== -1) {
      url = url.split('#')[0]
    }
    GetChatJsApiConfig({
      AccountId: webInfo.WxAccountId,
      // AccountId: 10053,
      Url: url
    }).then(data => {
      if (!data) {
        __IsWxJsError = true
        return
      }

      var config = data.Data
      wx.config({
        debug: false,
        appId: config.AppId,
        timestamp: config.Timestamp,
        nonceStr: config.NonceStr,
        signature: config.Signature,
        jsApiList: jsApiList,
        openTagList: ["wx-open-launch-weapp"],
      })
      wx.ready(function () {
        ___IsWxJsReady = true
        if (callback && callback instanceof Function) {
          callback()
        }
        
      })
      wx.error(function (res) {
        alert('wx error, ' + JSON.stringify(res))
        // __IsWxJsError = true;

        // 安卓手机有些浏览器会导致微信url签名失败，这里用原始地址请求一次
        // GetChatJsApiConfig({
        //   AccountId: webInfo.WxAccountId,
        //   Url: __originUrl
        // }).then(data => {
        //   if (!data) {
        //     __IsWxJsError = true
        //     return
        //   }
        //   var config = data.data
        //   wx.config({
        //     debug: false,
        //     appId: config.AppId,
        //     timestamp: config.Timestamp,
        //     nonceStr: config.NonceStr,
        //     signature: config.Signature,
        //     jsApiList: jsApiList
        //   })
        //   wx.ready(function() { })
        //   wx.error(function(res) {
        //     alert("wx error, " + JSON.stringify(res));
        __IsWxJsError = true
      })
      // })
      // })
    })
  }
}

export default GetWxJsConfig
